package adavance.thread;

/**
 * @author oldliu
 * @since 1.0
 */
public class Demo09Synchronized implements Runnable{
    private int ticket = 10;//抢到了第几张票
    private int num = 0;//还剩几张
    boolean flag = false;
    @Override
    public void run() {
        while (!flag){
            sale();
            try {
                Thread.sleep((long) (100*Math.random()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized  void sale(){
        if (ticket<=0) {
            flag = true;
            return;
        }
        ticket--;
        num++;

//        try {
//            Thread.sleep(1000);
//        } catch ( InterruptedException e ) {
//            e.printStackTrace();
//        }
        System.out.println(Thread.currentThread().getName() + "抢到了，第" + num + "张票，还剩" + ticket + "张票");

    }
}

class Demo09Test{
    public static void main(String[] args) {
        Runnable rnb = new Demo09Synchronized();
        Thread h01 = new Thread(rnb,"纳兰性德");
        Thread h02 = new Thread(rnb,"老王");
        Thread h03 = new Thread(rnb,"小二赵");


        h02.start();
        h03.start();
        h01.start();
    }
}